import { useRoute, useRouter } from 'vue-router'
import { Ref, ref, unref, UnwrapRef } from 'vue'
import { BaseDetailVo } from '@/base/api/BaseVo'
import { useTagsViewStoreWithOut } from '@/store/modules/tagsView'
import { useEventBus } from '@/hooks/event/useEventBus'

export const useBaseDetailView = <DetailType extends BaseDetailVo, EditType>(
  writeRef: Ref<ComponentRef<any>>,
  className: string
) => {
  const { query } = useRoute()
  const type = query.type as string

  const tagsViewStore = useTagsViewStoreWithOut()
  const route = useRoute()
  const router = useRouter()
  const eventBus = useEventBus()

  // 安全地获取并转换 id
  let id: number | undefined = undefined
  if (typeof query.id === 'string') {
    id = parseInt(query.id, 10)
    if (isNaN(id)) {
      console.error('Invalid id parameter')
      id = undefined
    }
  } else if (Array.isArray(query.id) && query.id.length > 0 && typeof query.id[0] === 'string') {
    id = parseInt(query.id[0], 10)
    if (isNaN(id)) {
      console.error('Invalid id parameter')
      id = undefined
    }
  }

  const currentRow = ref<DetailType | null>(null)
  const loading = ref(false)

  const title = ref('')
  if (type === 'edit') {
    title.value = '编辑'
  } else {
    title.value = '新增'
  }

  const baseLoadDetail = async (detailApi: (id: number) => Promise<IResponse<DetailType>>) => {
    if (id !== undefined) {
      const res = await detailApi(id)
      currentRow.value = res.data as UnwrapRef<DetailType | null>
    }
  }

  const baseSave = async (
    onEdit: (formData: EditType, id: number) => Promise<void>,
    onAdd: (formData: EditType) => Promise<void>
  ) => {
    loading.value = true
    const write = unref(writeRef)
    const formData = await write?.submit()
    if (formData) {
      try {
        if (type === 'edit' && id !== undefined) {
          formData['id'] = id
          await onEdit(formData, id)
        } else {
          await onAdd(formData)
        }
        eventBus.emit('refresh' + className)
        router.back()
        tagsViewStore.delView(route)
      } catch (error) {
        console.error('保存失败', error)
      } finally {
        loading.value = false
      }
    } else {
      console.warn('无法获取请求表单')
      loading.value = false
    }
  }

  const back = () => {
    router.back()
    tagsViewStore.delView(route)
  }

  return {
    type,
    id,
    title,
    currentRow,
    baseLoadDetail,
    baseSave,
    loading,
    back
  }
}
